Appendix G — Assignment 2

Author

phonchi

Published

May 28, 2023

G.1 (1) What statement creates a function?

  1. def
  2. definition
  3. Def
  4. Definition

Ans: Double click to answer the question

G.2 (2) According to the following program:

def math():   
    math = 100
    print(math)   

def nsysu():   
    math = "interesting"
    math()    
    print(math)  

math = "I love math!"  

What should the ouputs look like when you run nsysu() and print(math)?

  1. I love math! I love math!, I love math!
  2. interesting, I love math!
  3. 100 100, 100
  4. 100 interesting, I love math!

Ans: Double click to answer the question

G.3 (3) What does from math import * if you have a file named math.py, which stores many functions?

  1. import the first function in math.py
  2. import all functions from math.py
  3. import the last function in math.py
  4. meaningless

Ans: Double click to answer the question

G.4 (4) How do you use the function linspace() in numpy according to import numpy as np?

  1. linspace()
  2. np linspace()
  3. numpy.linspace()
  4. np.linspace()

Ans: Double click to answer the question

G.5 (5) What is the data type of None?

  1. str
  2. Nonetype
  3. bool
  4. list

Ans: Double click to answer the question

G.6 (6) Why are functions adventageous to have in your programs?

Ans: Double click to answer the question

Functions reduce the need for duplicate code. This makes programs shorter, easier to read, and easier to update.

G.7 (7) What happens to variables in a local scope when the function call returns?

Ans: Double click to answer the question

When a function returns, the local scope is destroyed, and all the variables in it are forgotten.

G.8 (8) How can you force a variable in a function to refer to the global variable?

Ans: Double click to answer the question

A global statement will force a variable in a function to refer to the global variable.

G.9 (9) Write a function named collatz() that has one parameter named number. If number is even, then collatz should print number // 2 and return this value. If number is odd, then collatz should print and return 3 * number + 1.

def collatz(number):
    """
    Parameters
    ----------
    number: int
        The input number.
    Returns
    -------
    number: int
        The ouput number.
    """
    # coding your answer here
    if number % 2 == 0:
        number = number // 2
    else:
        number = 3 * number + 1
    print(number)
    return(number)

G.10 (10) Continuing from the previous question, write a program that allows the user to type in an interger and that keeps callig collatz() on the number until the function returns the value 1.

sample output

Enter number:   
3      
10   
5   
16   
8   
4   
2   
1
# coding your answer here
number = int(input("Enter number: \n"))
while number != 1:
    number = collatz(number)